<?php

namespace common\models\goods;

use Yii;

/**
 * 这个模型基于表 "{{%goods_gallery}}" 生成。
 *
 * @property integer $id
 * @property integer $goods_id
 * @property string $img
 * @property integer $sort
 */
class GoodsGallery extends \common\models\AR {

    public $modelName = '';

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%goods_gallery}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['goods_id', 'sort'], 'integer'],
            [['img'], 'required'],
            [['img'], 'string', 'max' => 150]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'goods_id' => 'Goods ID',
            'img' => '图片路径',
            'sort' => 'Sort',
        ];
    }

    /**
     * 保存商品相册，将图片从临时文件夹中转移到正式文件夹
     * @param string $tmpPath 临时文件夹路
     * @return boolean 如果相册转移成功，返回TRUE，否则返回FALSE
     */
    public function saveImg($tmpPath) {
        if (empty($tmpPath)) {
            return FALSE;
        }

        $ext = pathinfo($tmpPath, PATHINFO_EXTENSION);
        $newFileName = uniqid().'.' . $ext;
        $formPath = Yii::getAlias('@temp') . '/' . $tmpPath;
        $t = \backend\models\Supplier::getImgPath('goodsGallery') . '/' . $newFileName;
        $newPath = Yii::getAlias('@img') . "/" . $t;

        $result=@rename($formPath, $newPath);
        if ($result) {
            $this->img = $t;
        }
        return $result;
    }
    
    public function afterDelete() {
        parent::afterDelete();
        if(!empty($this->img)){
            $filePath=Yii::getAlias('@img') . "/" . $this->img;
            @unlink($filePath);
        }
    }

}
